﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Enums;
using VideoSeller.Business.Models;
using VideoSeller.Web.Models;
using System.Web.Helpers;

namespace VideoSeller.Web.Controllers
{
	public class HomeController : BaseController
	{
		private readonly OnlineContentModel _onlineContentModel;
		private readonly OnlineRatingModel _onlineRatingModel;
		private readonly OnlineCategorizationModel _onlineCategorizationModel;
		private readonly CategoryModel _categoryModel;
		private readonly TeamChatModel _teamChatModel;
		private readonly WaitModel _waitModel;
		private readonly ContentModel _contentModel;
        private readonly CountryModel _countryModel;
        private readonly SettingsModel _settingsModel;
        private readonly ClientModel _clientModel;
        public HomeController(OnlineContentModel onlineContentModel, OnlineRatingModel onlineRatingModel, OnlineCategorizationModel onlineCategorizationModel, CategoryModel categoryModel, TeamChatModel teamChatModel, WaitModel waitModel, ContentModel contentModel, CountryModel countryModel, SettingsModel settingsModel, ClientModel clientModel)
		{
			_onlineContentModel = onlineContentModel;
			_categoryModel = categoryModel;
			_onlineCategorizationModel = onlineCategorizationModel;
			_teamChatModel = teamChatModel;
			_onlineRatingModel = onlineRatingModel;
			_waitModel = waitModel;
			_contentModel = contentModel;
            _settingsModel = settingsModel;
            _countryModel = countryModel;
            _clientModel = clientModel;
		}

		[ActionName("Index")]
		public ViewResult Capabilities()
		{
			var model = _contentModel.GetBlock("About");
			return View("Capabilities", model);
		}
     
        //public ViewResult UserRating()
        //{
        //    var model = new UserRatingViewModel();
        //    model.MRating = _clientModel.GetRatedM(10).ToList();
        //    model.CRating = _clientModel.GetRatedC(10).ToList();
        //    return View("UserRating",model);
        //}
		public ViewResult Online(FilterViewModel filter)
		{
			var model = GetContentListViewModel(OnlineContentType.Online, "Online", filter);
			return View(model);
		}

		public ViewResult Announcement(FilterViewModel filter)
		{
			var model = GetContentListViewModel(OnlineContentType.Announcement, "Announcement", filter);
			return View(model);
		}

		public ViewResult History(FilterViewModel filter)
		{
			var model = GetContentListViewModel(OnlineContentType.History, "History", filter);
			return View(model);
		}

		[HttpGet]
		public ViewResult NoContent()
		{
			return View();
		}

		[HttpGet]
		public ActionResult Content(int id)
		{
			var onlineContent = _onlineContentModel.GetOnlineContent(id);

			if (onlineContent == null)
			{
				return RedirectToAction("NoContent", "Home");
			}

			var model = new OnlineItemViewModel(onlineContent);
			model.ChatModel = new ChatViewModel
				{
					Id = id,
                    readOnly =(CurrentClient == null) || (onlineContent.OnlineContentType != OnlineContentType.Online
                    &&  !(onlineContent.OnlineContentType == OnlineContentType.Announcement && CurrentClient.UserId == onlineContent.Client.UserId))
                    ,
					ChatItems = _teamChatModel.GetChat(id).ToList()
				};
			model.CommentsModel = new CommentsViewModel
				{
					Id = id,
                    readOnly = onlineContent.OnlineContentType != OnlineContentType.Online,
					Messages = _onlineContentModel.GetOnlineContent(id).OnlineRatings.OrderByDescending(x => x.CreateTime).ToList()
				};

			return View(model);
		}

		[HttpPost]
		public ActionResult AddCommentMessage(CommentsViewModel model)
		{
			_onlineRatingModel.Rate(CurrentClient.UserId, model.Id, model.IsLike, model.NewMessage);

			return RedirectToAction("Content", "Home", new {id = model.Id});
		}

		[NonAction]
		public ContentListViewModel GetContentListViewModel(OnlineContentType onlineContentType, string filterAction, FilterViewModel filter)
		{
			var model = new ContentListViewModel
				{
					ShowRating = onlineContentType == OnlineContentType.Online,
					ShowWantToSee = CurrentMembershipUser != null &&  onlineContentType == OnlineContentType.Announcement,
					Items = filter.FilterType.HasValue && filter.FilterType == ContentListFilterType.Marked && CurrentMembershipUser != null
						        ? _waitModel.GetWantToSee(CurrentMembershipUser.UserId, onlineContentType)
						        : _onlineContentModel.GetAll(onlineContentType),
                                currentClient = CurrentClient,
                    AllCamParams = _settingsModel.QualityStrings,
                    WowzaPatch = _settingsModel.GetSetting("WowzaPath").Value
                    
				};
            
           
			var filterModel = new ContentListFilterViewModel
				{
					Action = filterAction,
					ShowMarkedFilter = CurrentMembershipUser != null,
					CurrentFilter = filter.FilterType.HasValue ? filter.FilterType.Value : ContentListFilterType.All,
                    SelectedCountry = filter.selectedCountry.HasValue ? filter.selectedCountry : null,
					Categories = _categoryModel.GetCategories(),
                    countryes = _countryModel.GetAll().OrderBy(c=> c.Name),
					PageNumber = filter.Page.HasValue ? filter.Page.Value : 1,
					PageSize = filter.PageSize.HasValue ? filter.PageSize.Value : 10
				};

			if (!string.IsNullOrEmpty(filter.Categories))
			{
				var catIds = filter.Categories.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
				filterModel.SelectedCategories = new List<Category>(catIds.Select(x => _categoryModel.GetCategory(int.Parse(x))));
				model.Items = model.Items.Join(_onlineCategorizationModel.GetAll(), content => content.Id, category => category.OnlineContentId,
									 (content, category) => new { ContentItem = content, CategoryItem = category })
									 .Where(contCat => catIds.Contains(contCat.CategoryItem.CategoryId.ToString()))
									 .Select(contCat => contCat.ContentItem).AsEnumerable().Distinct();
			}
			else if (!filter.FilterType.HasValue || filter.FilterType != ContentListFilterType.Marked)
			{
				model.Items = _onlineContentModel.GetAllWithoutLimited(onlineContentType);
			}

			if (!string.IsNullOrEmpty(filter.Languages))
			{
				var cultures = filter.Languages.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();

				filterModel.SelectedLanguages = cultures;
				model.Items = model.Items.Where(x => cultures.Contains(x.Culture));
			}
            if (filter.selectedCountry.HasValue)
            {
                model.Items = model.Items.Where(x => x.CountryId == filter.selectedCountry);
            }
			if (filter.PriceFilter.HasValue)
			{
				filterModel.PriceFilter = filter.PriceFilter.Value;

				if (filterModel.PriceFilter == PriceFilter.Free)
				{
					model.Items = model.Items.Where(x => !x.MinimalPrice.HasValue || x.MinimalPrice == 0);
				}
				else if (filterModel.PriceFilter == PriceFilter.Paid)
				{
					model.Items = model.Items.Where(x => x.MinimalPrice.HasValue && x.MinimalPrice > 0);
				}
			}

			if (filter.VideoType.HasValue && filter.VideoType.Value > 0)
			{
				filterModel.VideoTypeFilter = filter.VideoType.Value;
				model.Items = model.Items.Where(x => x.VideoContentTypeValue == (short) filter.VideoType.Value);
			}

			if (!string.IsNullOrEmpty(filter.Author))
			{
				model.Items = model.Items.Where(x => x.Client.Login.ToLower() == filter.Author.ToLower());
			}

			if (!string.IsNullOrEmpty(filter.Search))
			{
				model.Items = model.Items.Where(x => x.Title.ToLower().Contains(filter.Search.ToLower()) || x.Description.ToLower().Contains(filter.Search.ToLower()));
			}

			model.Items = model.Items.OrderByDescending(x => x.Id);
            if (filter.FilterType.HasValue && (filter.FilterType == ContentListFilterType.TimeAsc || filter.FilterType == ContentListFilterType.TimeDesc))
            {
                model.Items = filter.FilterType == ContentListFilterType.TimeAsc
                                  ? model.Items.OrderBy(x => x.BroadcastStart)
                                  : model.Items.OrderByDescending(x => x.BroadcastStart);
            }
            else
                if (!filter.FilterType.HasValue && filterAction == "History")
                    model.Items = model.Items.OrderByDescending(m => m.BroadcastEnd);

			var total = model.Items.Count();
			var skip = (filterModel.PageNumber - 1) * filterModel.PageSize;

			if (skip > total)
			{
				skip = 0;
			}

			model.Items = model.Items.Skip(skip).Take(filterModel.PageSize);
			var pageCount = total / filterModel.PageSize;

			if (total % filterModel.PageSize != 0)
			{
				pageCount = pageCount + 1;
			}

			filterModel.PageCount = pageCount;
			filterModel.Total = total;
			filterModel.Filter = filter;
			model.FilterViewModel = filterModel;

			return model;
		}
	}
}